<template>
  <div class="borrow-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="main-card">
          <template #header>
            <div class="card-header">
              <span>借阅操作台</span>
              <el-tag v-if="currentReader" type="success">当前用户：{{ currentReader.name }}</el-tag>
            </div>
          </template>

          <div v-if="!currentReader" class="scan-reader">
            <div v-if="!startScanning" class="start-scan-button">
              <el-button type="primary" size="large" @click="startScanningReader">
                <el-icon><VideoCameraFilled /></el-icon>
                开始扫描借阅证
              </el-button>
            </div>
            <div v-else class="scan-area">
              <SteamBarcodeReader
                ref="barcodeReader"
                @decode="handleReaderScan"
                :paused="!startScanning"
              />
              <el-button class="cancel-scan" @click="cancelScanningReader">取消扫描</el-button>
            </div>
          </div>
          <!-- 借阅证扫描完成后 -->
          <div v-else class="operation-area">
            <div class="action-buttons" v-if="!currentOperation">
              <el-button type="primary" size="large" @click="startBorrow">借阅图书</el-button>
              <el-button type="success" size="large" @click="startReturn">归还图书</el-button>
              <el-button type="warning" size="large" @click="handleBack">返回</el-button>
            </div>
            
            <!-- 扫描图书IBSN条形码 -->
            <div v-else class="scan-book">
              <div class="scan-area">
                <SteamBarcodeReader @decode="handleBookScan" :paused="!isBookScanning" />
              </div>
              <div class="scanned-books">
                <h4>已扫描图书</h4>
                <el-table :data="scannedBooks" style="width: 100%">
                  <el-table-column prop="title" label="书名" />
                  <el-table-column prop="author" label="作者" width="120" />
                  <el-table-column prop="location" label="位置" width="120" />
                  <el-table-column fixed="right" label="操作" width="100">
                    <template #default="scope">
                      <el-button
                        type="danger"
                        :icon="Delete"
                        circle
                        @click="removeBook(scope.$index)"
                        class="delete-btn"
                      />
                    </template>
                  </el-table-column>
                </el-table>
                <div class="action-footer">
                  <el-button type="primary" @click="handleConfirm">确认{{ currentOperation === 'borrow' ? '借阅' : '归还' }}</el-button>
                  <el-button @click="cancelOperation">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card v-if="currentReader" class="reader-info">
          <template #header>
            <div class="card-header">
              <span>读者信息</span>
            </div>
          </template>
          <div class="info-content">
            <p><label>姓名：</label>{{ currentReader.name }}</p>
            <p><label>学号：</label>{{ currentReader.studentId }}</p>
            <p><label>已借：</label>{{ currentReader.books.length }}/{{ maxBorrow }}本</p>
            <el-divider />
            <h4>当前借阅</h4>
            <el-table :data="currentReader.books" style="width: 100%">
              <el-table-column prop="title" label="书名" />
              <el-table-column prop="due_time" label="应还日期" width="120">
                <template #default="scope">
                  {{ new Date(scope.row.due_time).toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  }) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { VideoCameraFilled, Delete } from '@element-plus/icons-vue'; // 添加 Delete 图标
import { ElMessage } from 'element-plus';
import SteamBarcodeReader from "@/components/steambarcodereader.vue";
import { getUserBorrowInfoByCardno,getBookInfoByISBN,borrowBook,returnBook } from "@/api/index"; // 修改导入方式

const currentReader = ref(null);
const currentOperation = ref('');
const scannedBooks = ref([]);
const maxBorrow = 5;
// 读者证扫描对象
const readerCard = ref(null);
const startScanning = ref(false);
const isBookScanning = ref(false); // 添加图书扫描状态控制

const barcodeReader = ref(null);

// 添加组件销毁时的清理代码
onUnmounted(() => {
  if (barcodeReader.value) {
    startScanning.value = false;
    isBookScanning.value = false;
  }
});

// 修改用户数据映射函数
const mapUserData = (data) => ({
  id: data.user_id,
  name: data.real_name,
  studentId: data.studentno,
  books: data.borrowingBooks?.map(book => ({
    title: book.title,
    due_time: book.due_time,
    book_id: book.book_id
  })) || [],
  avatar: data.student_img
});

// 处理读者证扫描
const handleReaderScan = async (result) => {
  try {
    const cardno = result;
    readerCard.value = { cardno };  // 修正readerCard的赋值
    const response = await getUserBorrowInfoByCardno(readerCard.value);
    if (response.code === 200) {
      currentReader.value = mapUserData(response.data);
      ElMessage.success(`欢迎，${currentReader.value.name}`);
    } else {
      ElMessage.error(response.msg || '读者信息获取失败');
    }
  } catch (error) {
    console.error('获取读者信息错误:', error);
    ElMessage.error('读者信息获取失败');
  }
};

// 处理图书扫描
const handleBookScan = async (result) => {
  if (!currentOperation.value) return;
  
  try {
    // 检查是否重复扫描
    if (scannedBooks.value.some(book => book.isbn === result)) {
      ElMessage.warning('该图书已扫描');
      return;
    }

    // 构建请求参数，增加operation和user_id
    const params = {
      isbn: result,
      operation: currentOperation.value,
      user_id: currentReader.value.id
    };

    // 获取图书信息
    const response = await getBookInfoByISBN(params);
    
    // 处理不同的响应状态
    if (response.code === 200) {
      // 正常情况：可以借阅或归还
      if (currentOperation.value === 'borrow') {
        if (currentReader.value.books.length >= maxBorrow) {
          ElMessage.warning('已达最大借阅数量');
          return;
        }
      }
      
      const bookInfo = {
        title: response.data.title,
        author: response.data.author,
        location: response.data.location,
        book_id: response.data.book_id,
        isbn: result
      };
      
      scannedBooks.value.push(bookInfo);
      ElMessage.success(`成功扫描：${bookInfo.title}`);
    } else if (response.code === 230) {
      // 借阅时：用户已借阅过该书籍
      ElMessage.warning(response.msg || '用户已借阅过，请换一本书');
    } else if (response.code === 240) {
      // 归还时：用户未借阅该书籍
      ElMessage.warning(response.msg || '当前用户未借阅该书籍');
    } else {
      ElMessage.error(response.msg || '图书信息获取失败');
    }
  } catch (error) {
    console.error('获取图书信息错误:', error);
    ElMessage.error('图书信息获取失败');
  }
};

const startBorrow = () => {
  if (currentReader.value.books.length >= maxBorrow) {
    ElMessage.warning('已达最大借阅数量');
    return;
  }
  currentOperation.value = 'borrow';
  isBookScanning.value = true; // 开始扫描图书
};

const startReturn = () => {
  currentOperation.value = 'return';
  isBookScanning.value = true; // 开始扫描图书
};

const cancelOperation = () => {
  currentOperation.value = '';
  scannedBooks.value = [];
  isBookScanning.value = false; // 停止扫描图书
};

const removeBook = (index) => {
  scannedBooks.value.splice(index, 1);
};

const handleConfirm = async () => {
  if (scannedBooks.value.length === 0) {
    ElMessage.warning('请先扫描图书');
    return;
  }

  try {
    // 准备请求参数
    const params = {
      user_id: currentReader.value.id,
      books: scannedBooks.value.map(book => book.book_id)
    };

    // 根据当前操作调用相应的API
    const response = await (currentOperation.value === 'borrow' 
      ? borrowBook(params) 
      : returnBook(params));

    if (response.code === 200) {
      ElMessage.success(`${currentOperation.value === 'borrow' ? '借阅' : '归还'}成功`);
      // 刷新读者信息
      const readerResponse = await getUserBorrowInfoByCardno(readerCard.value);
      if (readerResponse.code === 200) {
        currentReader.value = mapUserData(readerResponse.data);
      }
      isBookScanning.value = false;
      cancelOperation();
    } else {
      ElMessage.error(response.msg || `${currentOperation.value === 'borrow' ? '借阅' : '归还'}失败`);
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(`${currentOperation.value === 'borrow' ? '借阅' : '归还'}失败`);
  }
};

const startScanningReader = () => {
  startScanning.value = true;
};

const cancelScanningReader = () => {
  startScanning.value = false;
  if (barcodeReader.value) {
    barcodeReader.value.stopScanning();
  }
};

const handleBack = () => {
  if (barcodeReader.value) {
    barcodeReader.value.stopScanning();
  }
  currentReader.value = null;
  readerCard.value = null;
  startScanning.value = false;
  currentOperation.value = '';
  scannedBooks.value = [];
};
</script>

<style scoped>
.borrow-container {
  padding: 20px;
}
.borrow-tabs {
  background: #fff;
  padding: 20px;
}
.ml-2 {
  margin-left: 10px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.scan-area {
  height: 330px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.scan-area :deep(video) {
  height: 250px;
  object-fit: cover;
}

.scan-placeholder {
  text-align: center;
  color: #909399;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 40px 0;
}

.scanned-books {
  margin-top: 20px;
}

.action-footer {
  margin-top: 20px;
  text-align: right;
}

.reader-info .info-content label {
  display: inline-block;
  width: 60px;
  color: #909399;
}

.start-scan-button {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.cancel-scan {
  margin-top: 10px;
}

.el-icon {
  margin-right: 8px;
}

.delete-btn {
  padding: 8px;
  font-size: 18px;
}
</style>
